package b3.widget.basic
{
	import flash.display.*;
	import flash.events.Event;

	public class GridShadowMovie extends BasicWidget
	{
		public static const DIRECTION_RIGHT:int = 0;
		public static const DIRECTION_LEFT:int = 2;
		public static const DIRECTION_UP:int = 3;
		public static const DIRECTION_DOWN:int = 1;
		
		public var color:int;
		public var direction:int;
		public var gridWidth:int;
		public var initDark:Number;
		public var gradientDark:Number;
		public var fadeSpeed:Number;
		public var screenWidth:Number;
		public var screenHeight:Number;
		 
		public function GridShadowMovie(width:Number, height:Number)
		{
			super();
			this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			this.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			gridWidth = 50;
			initDark = -0.6;
			gradientDark = 0.15;
			fadeSpeed = 0.4;
			color = 0x00AAFF;
			screenWidth = width;
			screenHeight = height;
			direction = 0;
		}
		
		private function onAddedToStage(event:Event):void
		{
			this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
			drawAll();
		}

		private function onRemovedFromStage(event:Event):void
		{
			this.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function onEnterFrame(event:Event):void
		{
			initDark -= fadeSpeed;
			if (!drawAll())
				close();
		}
		
		private function drawAll():Boolean
		{
			var drawFlag:Boolean = false;
			graphics.clear();
			var gridNumX:int = screenWidth / gridWidth + 1;
			var gridNumY:int = screenHeight / gridWidth + 1;
			for (var i:int = 0; i < gridNumX; i++)
			{
				for (var j:int = 0; j < gridNumY; j++)
				{
					var gradient:int;
					if (direction == 0)
						gradient = i;
					else if (direction == 1)
						gradient = j;
					else if (direction == 2)
						gradient = gridNumX - i - 1;
					else
						gradient = gridNumY - j - 1;
					var dark:Number = initDark + gradient * gradientDark;
					if (dark > 0)
					{
						drawGrid(gridWidth * i, gridWidth * j, dark);
						drawFlag = true;
					}
				}
			}
			return drawFlag;
		}
		
		private function drawGrid(x:Number, y:Number, dark:Number):void
		{
			if (dark > 0)
			{
				var darkWidth:Number = gridWidth * Math.min(dark, 1);
				graphics.beginFill(color, Math.min(dark, 1));
				graphics.drawRect(x + (gridWidth - darkWidth) / 2, y + (gridWidth - darkWidth) / 2, darkWidth, darkWidth);
				graphics.endFill();
			}
		}
		
	}
}